package zhongbo.java.air.monitor.listener;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;
import zhongbo.java.air.monitor.mapper.AirAlertLogMapper;
import zhongbo.java.air.monitor.mapper.AlertZoneMapper;
import zhongbo.java.air.monitor.model.AirAlertLog;
import zhongbo.java.air.monitor.model.AlertZone;
import zhongbo.java.air.monitor.model.PointDto;
import zhongbo.java.air.monitor.service.IJtsService;
import zhongbo.java.air.monitor.we.AlertZoneWebSocket;
import zhongbo.java.air.monitor.we.WebsocketAir;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Component
public class RedisSubscribeLogChanelListener implements MessageListener {
    @Autowired
    private AlertZoneMapper alertZoneMapper;
    @Autowired
    private AirAlertLogMapper airAlertLogMapper;
    @Autowired
    private IJtsService jtsService;


    @Override
    public void onMessage(Message message, byte[] pattern) {
        String msg = new String(message.getBody());
        System.out.println("收到消息：" + msg);
        WebsocketAir.WeAirs.values().forEach(WebSocket -> {
            try {
                WebSocket.session.getBasicRemote().sendText(msg);
            } catch (IOException ignored) {
            }
        });

        AirAlertLog(msg);
    }

    private void AirAlertLog(String msg) {
        JSONObject jsonObject = new JSONObject(msg);
        List<AlertZone> alertZones = getAlertZone();
        Double longitude = jsonObject.getDouble("longitude");
        Double latitude = jsonObject.getDouble("latitude");
        PointDto pointDto = new PointDto(latitude, longitude);
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(pointDto);
        String Icao = jsonObject.getStr("icaoCode");
        if (alertZones == null) {
            throw new RuntimeException("未配置预警区域");
        }
        alertZones.forEach(alertZone -> {
            List<PointDto> pointDtos = jtsService.parseAlertZoneVertices(alertZone.getVertices());
            if (jtsService.isInAlertZone(pointDtos, longitude, latitude)) {
                AirAlertLog airAlertLog = new AirAlertLog();
                airAlertLog.setIcaoCode(Icao);
                airAlertLog.setAlertZoneCode(alertZone.getZoneCode());
                airAlertLog.setAlertZoneId(alertZone.getId());
                airAlertLog.setTriggerCoordinates(jsonArray.toString());
                airAlertLog.setAlertType(alertZone.getZoneType());
                airAlertLog.setTriggerTime(jsonObject.getDate("timestamp"));
                airAlertLog.setStatus("0");
                System.out.println("在警戒区域内");
                QueryWrapper<AirAlertLog> queryWrapper = new QueryWrapper<>();
                Date fiveMinutesAgo = new Date(jsonObject.getDate("timestamp").getTime() - 60_000L);
                queryWrapper
                        .eq("icao_code", Icao)
                        .between("trigger_time", fiveMinutesAgo, jsonObject.getDate("timestamp"));
                Long JJQ = airAlertLogMapper.selectCount(queryWrapper);
                if (JJQ == 0) {
                    airAlertLogMapper.insert(airAlertLog);
                    System.out.println("警告日志插入成功");
                    QueryWrapper<AirAlertLog> queryWrapper1 = new QueryWrapper<>();
                    queryWrapper1.eq("icao_code", airAlertLog.getIcaoCode()).eq("trigger_time", airAlertLog.getTriggerTime());
                    AirAlertLog airAlertLog1 = airAlertLogMapper.selectOne(queryWrapper1);
                    JSONObject airAlertLogJson = new JSONObject(airAlertLog1);
                    AlertZoneWebSocket.WeAirs.values().forEach(WebSocket -> {
                        try {
                            WebSocket.session.getBasicRemote().sendText(airAlertLogJson.toString());
                        } catch (IOException ignored) {
                        }
                    });
                } else {
                    System.out.println("五分钟内已经存在警告日志");
                }
            }
        });
    }

    @Cacheable(value = "getAlertZone", key = "alert_history_[HuangYuJie]")
    public List<AlertZone> getAlertZone() {
        return alertZoneMapper.selectList(null);
    }

}
